package com.fsbm.ctech.maxis.ebpsbackend;

import sun.net.*;
import sun.net.ftp.*;
import java.io.*;
import java.text.*;
import java.util.*;
import java.util.Date;
import java.sql.*;

import com.fsbm.ctech.maxis.ebpsbackend.ConfigObject;
import com.fsbm.ctech.maxis.ebpsbackend.PrepareFiles;
import com.fsbm.ctech.maxis.ebpsbackend.DBLog;

/**
 * Transfers the data being passed from the different email related and sms components.
 * Uses Configuration Object for the SMTP and SMS Gateway related information.
 * <p>
 * Maxis Backend Program - Transfers information built locally to the SMTP and SMS servers.
 *
 * @author Michael Ty Chan
 */

public class TransferSubsDeliveryThread_v1r00 extends Thread{

    private static ConfigObject cfgObj = new ConfigObject();
	private String fileToPut;
	private String host;
	private String userID;
	private String password;
	private String TempDirectory;

	/**
	 *	Constructor
	 */
	public TransferSubsDeliveryThread_v1r00(String fileToPut, String host, String userID, String password, String TempDirectory) {
		this.fileToPut = fileToPut;
		this.host = host;
		this.userID = userID;
		this.password = password;
		this.TempDirectory = TempDirectory;

	}

	public void run() {

       long startTime; // Starting time of program, in milliseconds.
       long endTime;   // Time when computations are done, in milliseconds.
       double time;    // Time difference, in seconds.
       startTime = System.currentTimeMillis();
       int exitVal = -1;

       try {
          /* FtpClient ftpClient = new FtpClient();
           ftpClient.openServer(host);        // connect to FTP server
           ftpClient.login(userID, password); // login
           ftpClient.binary();                // set to binary mode transfer
           File file              = new File(fileToPut);
           TelnetOutputStream out = ftpClient.put(file.getName());
           FileInputStream in     = new FileInputStream(file);
           int c                  = 0;
           byte [] bytes          = new byte[204800];
           int total_bytes        = 0;
           System.out.println("Transferring -> " + fileToPut + " ...");
           System.out.println("\nTrying to transfer as much as 204,800 bytes/buffer");
           while ((c=in.read(bytes)) != -1 ) {
                 total_bytes += c;
                 System.out.println("Buffer transferred : " + total_bytes);
                 out.write(bytes, 0, c);
           }
           in.close();
           out.close();
           //ftpClient.closeServer();

           InputStream is = ftpClient.serverInput;
           BufferedReader buf = new BufferedReader(new InputStreamReader(is));

           String s = buf.readLine();
           System.out.println("["+s+"]");
*/

////////////////////////////////////////////////////////////////////////////////////////////
			String cmd = "scp "  + fileToPut + " " + userID + "@" + host + ":"+ fileToPut;
			//File wd = new File(strDir);
			System.out.println(cmd);
			Runtime rt = Runtime.getRuntime();
			Process proc = rt.exec(cmd);

            InputStream is = proc.getInputStream();
            BufferedReader buf = new BufferedReader(new InputStreamReader(is));

            String s = buf.readLine();
            System.out.println("["+s+"]");

			// any output?
			StreamGobbler outputGobbler = new
			StreamGobbler(is, "");

			// any error message?
			StreamGobbler errorGobbler = new
			StreamGobbler(proc.getErrorStream(), "ERR");

			// kick them off
			outputGobbler.start();
			errorGobbler.start();

			// any error???
			exitVal = proc.waitFor();
	        System.out.println("ExitValue: " + exitVal);

////////////////////////////////////////////////////////////////////////////////////////////


           String jobNo = "";

           int index = s.indexOf("JOB");
           if (index > -1){
               //226 JOB = 889794 - Transfer complete. (1151825 Bytes rcvd)
                String lastToken = "";
                StringTokenizer st = new StringTokenizer((String)s," ");
                int index0 = 0;
                while(st.hasMoreTokens()) {
                    if (lastToken.equals("=")){
                        jobNo = st.nextToken();
                        break;
                    }
                    lastToken = st.nextToken();
                }
           }

           int pos = fileToPut.lastIndexOf("/");
           DBLog.updateDeliveryRecord(jobNo,fileToPut.substring(pos+1),s);

           endTime = System.currentTimeMillis();
           time = (endTime - startTime) / 1000.0;
           System.out.println("Time it takes to transfer in seconds :" + time + "\n\n");

           PrepareFiles.BuildFileSet(fileToPut, TempDirectory);

        } catch (Exception ex) {
	       cfgObj.write("Trying to transfer to the SMTP server but failed ->" + fileToPut, "ErrSubs");
	       System.out.println("process(transferData): " + ex.getClass() + " " + ex.getMessage());
       }

	}
    	public static void printUsage() {
    	      System.out.println("\nCopyright (c) 2005 FSBM CTech Sdn Bhd (427095-M).");
    	      System.out.println("All rights reserved.");
    	      System.out.println("\n\nUsage : TransferSubscriptionEmail.sh [-threadCount=number of thread] ");
    	      System.out.println("\tor TransferSubscriptionEmail.sh -h for help options");
    	 }


	public static void main (String argv[]) {
		String strMaxThread = "";
		int maxThread = 10;
		for (int optind = 0; optind < argv.length; optind++) {
			if (argv[optind].toLowerCase().indexOf("-threadcount") != -1) {
                strMaxThread = argv[optind];
                strMaxThread = strMaxThread.substring(strMaxThread.indexOf("=")+1);
                maxThread = Integer.parseInt(strMaxThread);
            } else if (argv[optind].toLowerCase().startsWith("-h")) {
                printUsage();
                System.exit(1);
            } else {
                break;
            }
        }


           File f              = new File(cfgObj.pdfTransferDirectory);
           String fileToPut    = "";
           Vector vecFileNames = new Vector();
           Vector vecRunningThreads = new Vector();
           try{
               String files[]      = f.list();
               int vSize           = files.length;
               int intThreadCtr = 0;

               for(int i =0;i < vSize; i++){
				   fileToPut = cfgObj.pdfTransferDirectory + files[i].toString();
				   TransferSubsDeliveryThread_v1r00 t = new TransferSubsDeliveryThread_v1r00(fileToPut, cfgObj.ftpSMTPAddress, cfgObj.ftpSMTPUser, cfgObj.ftpSMTPPassword, cfgObj.pdfTempDirectory);
				   vecFileNames.addElement(t);
			   }

			   while(true){
				   if(vecFileNames.size()<=0 && vecRunningThreads.size()<=0) break;

				   for(int j=0;j<vecRunningThreads.size();j++){
					   TransferSubsDeliveryThread_v1r00 runningSubs = (TransferSubsDeliveryThread_v1r00)vecRunningThreads.elementAt(j);
					   if (runningSubs.isAlive() == false){
						   vecRunningThreads.removeElementAt(j);
					   }
				   }

				   if ((vecRunningThreads.size() < maxThread ) && (vecFileNames.size() > 0)){
					   TransferSubsDeliveryThread_v1r00 fileName = (TransferSubsDeliveryThread_v1r00)vecFileNames.firstElement();
					   fileName.start();
					   vecRunningThreads.addElement(fileName);
					   vecFileNames.removeElement(fileName);
				   }

				   try{
					   Thread.sleep(5000);
				   }catch(InterruptedException ie){
					   System.out.println("Exception is....."+ie);
				   }
			   }

        } catch (Exception ex) {
            cfgObj.write("process(TransferSubsDelivery): " + ex.getClass() + " " + ex.getMessage() + fileToPut, "ErrSubs");
        }

	}




}
